package com.hqyj.system.shiro;


import com.hqyj.system.model.User;
import com.hqyj.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName CustomRealm
 * @Description
 * @Author zlf
 * @Date 2021/9/17 10:36
 * @Version 1.0
 **/
//shiro的域对象
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    public UserService userService;
    //1.认证
    //登录认证时会进入这个方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.认证
        // ---->第一步从token中取出身份信:token是用户输入的
        String username = (String) authenticationToken.getPrincipal();
//        System.out.println("-------------------------------" + username);
        User user_db = userService.queryUserByUserName(username);
        //如果查询不到
        if (user_db==null){
            return null;
        }
        //获取当前用户的会话
        Session session = SecurityUtils.getSubject().getSession();
        //把用户信息保存导session
        session.setAttribute("USER",user_db);
        //准备数据
        String password = user_db.getPassword();
        //获得realm的名称
        String realmName = this.getName();
        //盐
        String salt = user_db.getSalt();
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(salt), realmName);
        return simpleAuthenticationInfo;
    }

    //2.授权
    //需要授权时会进入这个方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

}
